package org.wu.framework.inner.lazy.orm.spring.processor;

import org.wu.framework.lazy.orm.core.config.LazyOperationAttribute;
import org.wu.framework.lazy.orm.core.config.prop.LazyDataSourceAttribute;
import org.wu.framework.lazy.orm.database.sql.expand.database.persistence.factory.LazyDataSourcePropertiesFactory;
import org.wu.framework.lazy.orm.core.source.adapter.SourceFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;

/**
 * description Lazy schema 自动创建数据库
 *
 * @author Jia wei Wu
 * @date 2022/12/14 4:15 下午
 */
@Slf4j
@AutoConfigureOrder(value = Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnProperty(prefix = LazyOperationAttribute.LAZY_OPERATION_CONFIG_PREFIX, value = "enable-auto-schema", havingValue = "true")
@ConditionalOnBean(LazyDataSourceAttribute.class)
public class LazySchemaAutoCreateProcessor implements Ordered, InitializingBean {

    private final LazyDataSourceAttribute lazyDataSourceAttribute;

    public LazySchemaAutoCreateProcessor(LazyDataSourceAttribute lazyDataSourceAttribute) {
        this.lazyDataSourceAttribute = lazyDataSourceAttribute;
    }

    /**
     * Invoked by the containing {@code BeanFactory} after it has set all bean properties
     * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
     * <p>This method allows the bean instance to perform validation of its overall
     * configuration and final initialization when all bean properties have been set.
     *
     */
    @Override
    public void afterPropertiesSet() {
        try {
            //创建数据库
            LazyDataSourcePropertiesFactory.initSchema(lazyDataSourceAttribute);
            log.info("初始化数据库:【{}】成功",SourceFactory.getUrlSchema(lazyDataSourceAttribute.getUrl()));
        } catch (Exception e) {
            e.printStackTrace();
            log.info("自动治愈数据库失败");
        }
    }

    /**
     * Get the order value of this object.
     * <p>Higher values are interpreted as lower priority. As a consequence,
     * the object with the lowest value has the highest priority (somewhat
     * analogous to Servlet {@code load-on-startup} values).
     * <p>Same order values will result in arbitrary sort positions for the
     * affected objects.
     *
     * @return the order value
     * @see #HIGHEST_PRECEDENCE
     * @see #LOWEST_PRECEDENCE
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
